package com.geen.tuoke.ui.activity.phone

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentResolver
import android.content.Intent
import android.content.IntentFilter
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.geen.tuoke.R
import com.geen.tuoke.base.BaseActivity
import com.geen.tuoke.base.EmptyViewModel
import com.geen.tuoke.databinding.ActivityPhoneNumberBinding
import com.geen.tuoke.databinding.ItemPhoneCallBinding
import com.geen.tuoke.ui.activity.AddOrEditCustomerActivity
import com.geen.tuoke.ui.dialog.DialogPhoneCall
import com.geen.tuoke.ui.dialog.DialogTaskPhoneAutoCall
import com.geen.tuoke.ui.dialog.DialogTip
import com.geen.tuoke.ui.viewmodel.CustomerViewModel
import com.geen.tuoke.ui.viewmodel.PhoneNumberVm
import com.geen.tuoke.utils.CallUtil
import com.geen.tuoke.utils.LogUtils
import com.geen.tuoke.utils.PhoneStateReceiver
import com.geen.tuoke.utils.ext.checkAppPermission
import com.geen.tuoke.utils.ext.initClose
import kotlinx.android.synthetic.main.include_toolbar.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.Exception

/**
 * @Author LuoJi
 * @Date 2021/12/24-9:58
 * @Desc
 */
class PhoneNumberActivity : BaseActivity<PhoneNumberVm, ActivityPhoneNumberBinding>() {

    private lateinit var phoneStateReceiver: PhoneStateReceiver

    private val startForResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
            if (result.resultCode == Activity.RESULT_OK) {
                val intentData = result.data
                var uri = intentData?.data as Uri
                var result = getPhoneContacts(uri)
                LogUtils.debugInfo("电话号码" + result?.getOrNull(0) + result?.getOrNull(1))
                result?.let {
                    mViewModel.mobileNumber.value = it.getOrNull(1)?.replace(" ", "")
                }
            }
        }

    private val autoCallDialog: DialogPhoneCall by lazy {
        DialogPhoneCall(this, onClickCustomer = {
            //点击添加客户 判断是否是用户
            mViewModel.getCustomerInfoByMobile()
        }, updateTask = {
            //更新
            it.mobile = mViewModel.mobileNumber.value.toString()
            mViewModel.updatePhoneTask(it)
        })
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_phone_number
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        with(mBinding) {
            lifecycleOwner = this@PhoneNumberActivity
            viewModel = mViewModel
        }
        toolbar.initClose("手动拨号") {
            finish()
        }
        initView()

        mViewModel.callOutSuccess.observe(this, {
            mViewModel.commonUILiveData.showDialog.postValue("拨号中")
        })

        mViewModel.showCallResultMsg.observe(this, {
            if (it.isNotEmpty()) {
                DialogTip(this, it.toString()).showDialog()
            }
        })

        registerReceiverByPhoneState()
    }

    override fun initData() {
        val customerViewModel = ViewModelProvider(this).get(CustomerViewModel::class.java)
        customerViewModel.getLabelList()
        customerViewModel.labelList.observe(this,{
            autoCallDialog.setLabelData(it)
        })

        mViewModel.customerInfo.observe(this,{
            if(it!=null){
                AddOrEditCustomerActivity.start(this, it)
            }else{
                AddOrEditCustomerActivity.start(this, null)
            }
        })

    }

    @SuppressLint("SetTextI18n")
    private fun initView() {

        mBinding.ivContact.setOnClickListener {
            //检查权限
            checkAppPermission(Manifest.permission.READ_CONTACTS, callBack = {
                startForResult.launch(
                    Intent(
                        Intent.ACTION_PICK,
                        ContactsContract.Contacts.CONTENT_URI
                    )
                )
            })
        }

        mBinding.viewCallPhone.setOnClickListener {
            //拨打电话
            val phoneNumber = mBinding.tvPhoneNumber.text
            if (phoneNumber.isNullOrEmpty()) {
                return@setOnClickListener
            }
            checkAppPermission(Manifest.permission.CALL_PHONE, callBack = {
                //先调用接口
                mViewModel.callOut()
            })
        }

        val mAdapter = object :
            BaseQuickAdapter<String, BaseDataBindingHolder<ItemPhoneCallBinding>>(R.layout.item_phone_call) {
            override fun convert(
                holder: BaseDataBindingHolder<ItemPhoneCallBinding>,
                item: String
            ) {
                with(holder.dataBinding!!) {
                    phoneNumber = item
                    executePendingBindings()
                }
            }
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val text = mBinding.tvPhoneNumber.text
            val clickNumber = mAdapter.getItem(position)
            if (clickNumber == "x") {
                if (text.isNullOrEmpty()) {
                    return@setOnItemClickListener
                }
                mBinding.tvPhoneNumber.text = text.substring(0, text.length - 1)
            } else {
                mBinding.tvPhoneNumber.text = text.toString() + clickNumber
            }
        }
        mBinding.mRecycleView.adapter = mAdapter

        val phoneNumbers =
            arrayListOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "x")
        mAdapter.setList(phoneNumbers)
    }

    private fun getPhoneContacts(uri: Uri): Array<String?>? {
        val contact = arrayOfNulls<String>(2)
        try {
            //得到ContentResolver对象**
            val cr: ContentResolver = contentResolver
            //取得电话本中开始一项的光标**
            val cursor: Cursor = cr.query(uri, null, null, null, null)!!
            if (cursor != null) {
                cursor.moveToFirst()
                //取得联系人姓名**
                val nameFieldColumnIndex =
                    cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
                contact[0] = cursor.getString(nameFieldColumnIndex)
                //取得电话号码**
                val ContactId =
                    cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))
                val phone: Cursor = cr.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null
                )!!
                if (phone != null) {
                    phone.moveToFirst()
                    contact[1] =
                        phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                }
                phone.close()
                cursor.close()
            } else {
                return null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return contact
    }

    override fun onPause() {
        super.onPause()
        mViewModel.commonUILiveData.dismissDialog.postValue(false)
    }

    //接通时 对应的时间戳 【因现在监听不到接通状态 通过对比通话记录第一条数据判断是否为当前有效通话】
    var openTimeStamp: Long = 0
    private fun registerReceiverByPhoneState() {
        phoneStateReceiver = PhoneStateReceiver(object : PhoneStateReceiver.OnPhoneListener {
            override fun onOpen(phone: String) {
                openTimeStamp = System.currentTimeMillis()
            }

            override fun onClose() {
                // todo 弹框，接口返回值
                mViewModel.commonUILiveData.dismissDialog.postValue(false)
                // 弹框
                autoCallDialog.showAutoDialog(mViewModel.mobileNumber.value.toString(), mViewModel.callOutResult.value!!.toInt())
            }
        })
        val intentFilter = IntentFilter()
        intentFilter.addAction("android.intent.action.PHONE_STATE")
        registerReceiver(phoneStateReceiver, intentFilter)
    }
}